package widget.utils;

import android.content.Context;
import android.text.TextUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import library.logger.Logger;


/**
 * Created by Mr.Fan on 2016/11/6.
 */

public class AssetsUtils {
    private static final String ASSETS_PATH = "file:///android_asset";
    private static final String ASSETS = "assets";

    private final Context context;

    private AssetsUtils(Context context) {
        this.context = context;
    }

    public static AssetsUtils obtain(Context context) {
        return new AssetsUtils(context);
    }


    private static File checkTemp(File origin) {
        return new File(origin + ".tmp");
    }

    public File copyAssetsFile(final String from, final File target, boolean overwrite) throws IOException {
        if (target != null && !TextUtils.isEmpty(from))
            return copyAssetsFile(from, target.getAbsolutePath(), overwrite);
        return null;
    }

    public File copyAssetsFile(final String from, final String target, boolean overwrite) throws IOException {
        if (TextUtils.isEmpty(from) || TextUtils.isEmpty(target))
            return null;
        final String path = from.startsWith(File.separator) ? from.substring(1) : from;

        File file = new File(target);
        File tmp = checkTemp(file);
        InputStream is = null;
        OutputStream os = null;
        if (tmp.exists()) {
            tmp.delete();
            file.delete();
        } else if (file.exists()) {
            if (overwrite) {
                file.delete();
            } else
                return file;
        } else {
            File parent = file.getParentFile();
            if (parent != null && !parent.exists())
                parent.mkdirs();
        }
        try {
            is = context.getAssets().open(path);
            os = new FileOutputStream(tmp);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = is.read(buffer)) != -1) {
                os.write(buffer, 0, length);
            }
            os.flush();
            if (tmp.renameTo(file))
                return file;
        } finally {
            Logger.simple("copy Assets [ " + (file.exists() ? "√" : "Ｘ") + " ] :\"" + from + "\" To File: \"" + file + "\";");
            if (is != null)
                try {
                    is.close();
                } catch (IOException e) {
                }
            if (os != null)
                try {
                    os.close();
                } catch (IOException e) {
                }
        }
        return null;
    }
}
